package com.hmdp.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service(value = "userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendMsg(String phone, HttpSession httpSession) {
        //1.手机号格式验证
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }

        //2.生成验证码
        String code = RandomUtil.randomNumbers(4);

        //3.保存进session，并发送
//        httpSession.setAttribute("tel:code"+phone,code);
        //拿到String操作类
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        //设置60s的超时时间
        stringStringValueOperations.set(RedisConstants.LOGIN_CODE_KEY+phone,code,60, TimeUnit.SECONDS);

        log.info("用户{}的验证码为：{}", phone, code);//模拟发送验证码

        //4.返回成功
        return Result.ok();
    }

    @Override
    public User createUserWithPhone(String phone) {
        //创建用户
        User user = new User();
        //设置手机号
        user.setPhone(phone);
        //设置昵称(默认名)，一个固定前缀+随机字符串
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(3));
        this.save(user);
        return user;
    }
}
